<template>
  <div class='sub-sort'>
    <div class="sort">
      <a href="javascript:;" :class="{active:i.sortField===obj.sortField&&i.sortField!=='price'}" @click="select(i.sortField)" v-for="i in arr" :key="i.id">{{i.name}}
        <i :class="{active:obj.sortMethod==='asc'}" class="arrow up"  v-if="i.sortField==='price'"/>
        <i :class="{active:obj.sortMethod==='desc'}" class="arrow down" v-if="i.sortField==='price'"/>
      </a>

    </div>
    <div class="check">
      <XtxCheckbox v-model="obj.inventory" >仅显示有货商品</XtxCheckbox>
      <XtxCheckbox v-model="obj.onlyDiscount" >仅显示特惠商品</XtxCheckbox>
    </div>
  </div>
</template>
<script>
import { ref, reactive, watch } from 'vue'
import { useRoute } from 'vue-router'
export default {
  name: 'SubSort',
  setup (props, { emit }) {
    // 处理发送请求前的数据
    const arr = ref([{ id: 1, name: '默认排序', sortField: null },
      { id: 2, name: '最新商品', sortField: 'publishTime' },
      { id: 3, name: '最高人气', sortField: 'orderNum' },
      { id: 4, name: '评论最多', sortField: 'evaluateNum' },
      { id: 5, name: '价格排序', sortField: 'price' }
    ])
    const obj = reactive({
      inventory: false,
      onlyDiscount: false,
      sortField: null,
      sortMethod: null
    })
    const select = (val) => {
      obj.sortField = val
      if (val === 'price') {
        if (!obj.sortMethod) obj.sortMethod = 'desc'
        else obj.sortMethod = obj.sortMethod === 'desc' ? 'asc' : 'desc'
      } else obj.sortMethod = null
    }
    watch(obj, (val) => {
      emit('objChange', val)
    })
    // 路由发生变化，筛选条件重设为默认值
    const route = useRoute()
    watch(() => route.params.id, (id) => {
      if (route.path === `/category/sub/${id}`) {
        obj.inventory = false // 是否有库存
        obj.onlyDiscount = false // 只显示特惠
        obj.sortField = null // 排序字段
        obj.sortMethod = null// 当排序字段为价格时，价格的排序方式
      }
    })
    return { arr, obj, select }
  }
}
</script>
<style scoped lang='less'>
.sub-sort {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .sort {
    display: flex;
    a {
      height: 30px;
      line-height: 28px;
      border: 1px solid #e4e4e4;
      padding: 0 20px;
      margin-right: 20px;
      color: #999;
      border-radius: 2px;
      position: relative;
      transition: all .3s;
      &.active {
        background: @xtxColor;
        border-color: @xtxColor;
        color: #fff;
      }
      .arrow {
        position: absolute;
        border: 5px solid transparent;
        right: 8px;
        &.up {
          top: 3px;
          border-bottom-color: #bbb;
            &.active {
            border-bottom-color: @xtxColor;
          }
        }
        &.down {
          top: 15px;
          border-top-color: #bbb;
          &.active {
            border-top-color: @xtxColor;
          }
        }
      }
    }
  }
  .check {
    .xtx-checkbox {
      margin-left: 20px;
      color: #999;
    }
  }
}
</style>
